﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Windows.Browser;

namespace HackingSilverlightCodeBrowser
{
    public partial class MainPage : UserControl
    {
        public string ThisVersion = "14";
        public string ThisVersionPrefix = "v4.5.";
        public string DefaultSearch = "XAML";
        public HSLCollection SourceCodeLibrary = new HSLCollection();
        public ObservableCollection<CodeTag> TagsForTagCloud = new ObservableCollection<CodeTag>();

        public MainPage()
        {
            InitializeComponent();

            try
            {
                string URL = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri; 

                if (Application.Current.InstallState == InstallState.Installed && URL.IndexOf("http") == -1)
                {
                    MakeWork();
                }
                else if (URL.ToLower().IndexOf("hackingsilverlightcodebrowser") > -1)
                {
                    MakeWork();
                }
            }
            catch (Exception)
            {
                MakeWork();
            }  
        } 

        private void MakeWork()
        {

            InstallMe.Visibility = Visibility.Collapsed;

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            VersionBx.Text = ThisVersionPrefix + ThisVersion;
            SearchBox.Text = DefaultSearch;
            BuildTagCloud();

            // see if there is a new version on the server
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadCompleted);
            client.DownloadStringAsync(new Uri("http://www.HackingSilverlight.net/hslcb.version.xml"));
        }

        
        void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e) 
        {
            try 
            {
                if (!string.IsNullOrEmpty(e.Result)) 
                {
                    string temp = (string)(e.Result);
                    temp = (temp.Split('>'))[1];
                    temp = (temp.Split('<'))[0];

                    int ServerVersion = int.Parse((string)(temp));
                    int _ThisVersion = int.Parse(ThisVersion);

                    if (ServerVersion > _ThisVersion)
                    {
                        NewVersion.Visibility = Visibility.Visible; 
                    } 
                } 
            } 
            catch (Exception) 
            {
 
            } 
        } 


        #region tag cloud

        private void BuildTagCloud()
        {
            for (int x = 0; x < SourceCodeLibrary.Collection.Count; x++)
            {
                string[] TheseTags = SourceCodeLibrary.Collection[x].Tags.Split('~');
                for (int z = 0; z < TheseTags.Length; z++)
                {
                    bool IFoundIt = false;

                    for (int y = 0; y < TagsForTagCloud.Count; y++)
                    {
                        if (TheseTags[z].ToLower() == TagsForTagCloud[y].Tag.ToLower())
                        {
                            TagsForTagCloud[y].Occurence = TagsForTagCloud[y].Occurence + 1;
                            IFoundIt = true;
                        }
                    }
                    if (!IFoundIt)
                    {
                        TagsForTagCloud.Add(new CodeTag(TheseTags[z].ToLower()));
                    }
                }
            }

            for (int w = 0; w < TagsForTagCloud.Count; w++)
            {
                if (TagsForTagCloud[w].Occurence > 1)
                {
                    TextBlock ThisTagText = new TextBlock();
                    ThisTagText.Text = TagsForTagCloud[w].Tag;
                    ThisTagText.FontSize = (double.Parse(TagsForTagCloud[w].Occurence.ToString()) * 2) + 4;
                    ThisTagText.Margin = new Thickness(5, 0, 5, 0);
                    if (ThisTagText.FontSize > 24)
                    {
                        ThisTagText.FontSize = 24;
                    }
                    ThisTagText.Foreground = new SolidColorBrush(Color.FromArgb(250, 250, 250, 250));
                    ThisTagText.MouseLeftButtonDown += new MouseButtonEventHandler(ThisTagText_MouseLeftButtonDown);
                    TagCloudPanel.Children.Add(ThisTagText);
                }
            }

            TagCloudPanel.InvalidateArrange();
        }

        void ThisTagText_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            TextBlock ThisBlock = sender as TextBlock;
            SearchBox.Text = ThisBlock.Text.ToLower();
        }

        #endregion

        private void InstallMeButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (Application.Current.InstallState != InstallState.Installed)
            {
                Application.Current.Install();
            }
        }

        private void SearchBox_SelectionChanged(object sender, RoutedEventArgs e)
        {
            // do search... 
            CodeSamplesList.Items.Clear();

            string SearchText = SearchBox.Text.ToLower();

            if (SearchText.Length > 2)
            {
                for (int x = 0; x < SourceCodeLibrary.Collection.Count; x++)
                {
                    if (SourceCodeLibrary.Collection[x].Tags.IndexOf(SearchText) > -1)
                    {
                        ListBoxItem NewItem = new ListBoxItem();

                        TextBlock NewTextBlock = new TextBlock();
                        NewTextBlock.Text = SourceCodeLibrary.Collection[x].Title;
                        NewTextBlock.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
                        NewItem.Content = NewTextBlock;
                        NewItem.Tag = SourceCodeLibrary.Collection[x].Title;

                        CodeSamplesList.Items.Add(NewItem);
                    }
                }
            }
        }

        public void PresentTagSearch(string Tag)
        {
            SearchBox.Text = Tag;
        }

        private void ResetButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            SearchBox.Text = "";
        }

        private void TestBtn_Click(object sender, RoutedEventArgs e)
        {
            SearchBox.Text = "xaml";
        }

        private void CodeSamplesList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (CodeSamplesList.Items.Count > 0)
            {
                ListBoxItem thisItem = CodeSamplesList.SelectedItem as ListBoxItem;
                string ThisTitle = thisItem.Tag.ToString();

                MyCodeBlock ThisBlock = new MyCodeBlock(ThisTitle, this.ActualWidth);
                ThisBlock.Height = this.ActualHeight;
                ThisBlock.Width = this.ActualWidth;
                ThisBlock.Show();
            }
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        { 
            MyHyperLink button = new MyHyperLink("http://www.HackingSilverlight.net"); 
        }

        private void ContributorsBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Contributors ThisBlock = new Contributors();
            ThisBlock.Height = this.ActualHeight;
            ThisBlock.Width = this.ActualWidth;
            ThisBlock.Show();
        }

        private void HelpButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            HelpScreen ThisHelpScreen = new HelpScreen();
            ThisHelpScreen.Height = this.ActualHeight;
            ThisHelpScreen.Width = this.ActualWidth;
            ThisHelpScreen.Show();
        }

        private void EmailLink_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MyHyperLink button = new MyHyperLink("mailto:pieseczek@hotmail.com?Subject=HackingSilverlight Code Browser New Addition"); 
        }

        private void NewVersion_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MyHyperLink button = new MyHyperLink("http://www.hackingsilverlight.net/"); 
        }
    }
}
